package controller;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

import javax.ejb.EJB;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.json.JSONArray;
import org.json.JSONObject;

import serviceInterface.ScheduleServiceInterface;
import serviceInterface.UserServiceInterface;
import util.DateUtil;
import domain.Envelope;
import domain.Location;
import domain.EnvelopeType;
import domain.Mission;
import domain.POS;

/**
 * Servlet implementation class AJAXCotroller
 */
public class AJAXCotroller extends HttpServlet {
	private static final long serialVersionUID = 1L;
	
	@EJB
	ScheduleServiceInterface scheduleService;
	
	@EJB
	UserServiceInterface userService;
	
    /**
     * @see HttpServlet#HttpServlet()
     */
    public AJAXCotroller() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		String todo = request.getParameter("todo");
		
		if(todo.equals("getPOS")){
			String scheduleId = request.getParameter("scheduleId");
			List<POS> posList = scheduleService.getPOS(Integer.parseInt(scheduleId));
			
			JSONObject json = createPosJSON(posList);
			  
			response.setContentType("application/json");
			PrintWriter out = response.getWriter();
			out.print(json);
			out.flush();
		}else if(todo.equals("getUnPrioritizePOS")){
			String scheduleId = request.getParameter("scheduleId");
			List<POS> posList = scheduleService.getUnPrioritizePOS(Integer.parseInt(scheduleId));
			
			JSONObject json = createPosJSON(posList);
			  
			response.setContentType("application/json");
			PrintWriter out = response.getWriter();
			out.print(json);
			out.flush();
		}else if(todo.equals("getMission")){
			String scheduleId = request.getParameter("scheduleId");
			List<Mission> missions = scheduleService.getMission(Integer.parseInt(scheduleId));
			
			JSONObject json = createMissionJSON(missions);
			  
			response.setContentType("application/json");
			PrintWriter out = response.getWriter();
			out.print(json);
			out.flush();
		}else if(todo.equals("getLocation")){
			String scheduleId = request.getParameter("scheduleId");
			Location location = scheduleService.getCurrentLocation(Integer.parseInt(scheduleId));
			JSONObject json = null;
			if(location!=null)
				json = createLocationJSON(location);
			
			response.setContentType("application/json");
			PrintWriter out = response.getWriter();
			out.print(json);
			out.flush();
		}else if(todo.equals("checkMissionTransferCase")){
			String missionId = request.getParameter("missionId");
			Mission mission = scheduleService.getMissionDetailForTransfer(Integer.parseInt(missionId));
			JSONObject json = createMissionDetail(mission);
			response.setContentType("application/json");
			PrintWriter out = response.getWriter();
			out.print(json);
			out.flush();
			
		}
	}
	
	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		String todo = request.getParameter("todo");
		if(todo.equals("updateLocation")){ 
			String personId = request.getParameter("personId");
			String currentLat = request.getParameter("currentLat");
			String currentLng = request.getParameter("currentLng");
			
			Location location = new Location();
				location.setLatitute(Double.parseDouble(currentLat));
				location.setLongtitute(Double.parseDouble(currentLng));
			userService.updateLocation(Integer.parseInt(personId), location);
		}
	}
	
	public JSONObject createPosJSON(List<POS> posList){
		JSONObject j = new JSONObject();
		JSONArray jsonArray = new JSONArray();
		  for (int i=0; i<posList.size(); i++) {
			  JSONObject json = new JSONObject();
			  POS posTemp = posList.get(i);
			  json.put("id",posTemp.getId());
			  json.put("name", posTemp.getName());
			  json.put("lat", posTemp.getLatitute());
			  json.put("lng", posTemp.getLongtitute());
			  json.put("isCentral", posTemp.isCentralGroup());
			  if(posTemp.getMission()!=null){
				  json.put("missionId", posTemp.getMission().getId());
			  }else {
				  System.out.println("Mission -> "+posTemp.getMission());
			  }
			  jsonArray.put(json);
		  }
		j.put("pos", jsonArray);
		return j;
	}
	
	public JSONObject createMissionJSON(List<Mission> missionList){
		JSONObject j = new JSONObject();
		JSONArray jsonArray = new JSONArray();
//		  for (int i=0; i<missionList.size(); i++) {
//			  
//		  }
		  for(int i=0; i<missionList.size(); i++){
			  JSONObject json = new JSONObject();
			  Mission missionTemp = missionList.get(i);
					POS pos = missionTemp.getToPOS();
					String completeStr = "";
					if(missionTemp.getCompleteTime()!=null){
						completeStr = DateUtil.getDDMMYYYYHHMMFromTimestamp(missionTemp.getCompleteTime());
					}
					json.put("id",pos.getId());
					json.put("priority", missionTemp.getPriority());
					json.put("completetime", completeStr);
					json.put("status", missionTemp.getStatus().toString());
					json.put("endtime", missionTemp.getEndTime());
					json.put("toPosName", pos.getName());
					json.put("toPosLat", pos.getLatitute());
				    json.put("toPosLng", pos.getLongtitute());
				  jsonArray.put(json);
			}
		j.put("mission", jsonArray);
		return j;
	}
	public JSONObject createMissionDetail(Mission mission){
		boolean isTransfer = false;
		JSONObject j = new JSONObject();
		JSONArray jsonArray = new JSONArray();
		  	JSONObject json = new JSONObject();
			json.put("id", mission.getId());
			for(Envelope env:mission.getEnvelopes()){
				if(env.getEnvelopeType() == EnvelopeType.transfer){
					System.out.println("envelopId = "+env.getId());
					isTransfer = true;
					json.put("transfer", "transfer");
					json.put("transferToPOS", env.getTransferTo().getId());
					json.put("transferFromPOS", env.getTransferFrom().getId());
				}
			}
			if(!isTransfer){
				json.put("transfer", " ");
			}
			json.put("toPOS", mission.getToPOS().getId());
			jsonArray.put(json);
		j.put("mArray", jsonArray);
		return j;
		
	}

	
	public JSONObject createLocationJSON(Location location){
		JSONObject j = new JSONObject();
		  j.put("id",location.getId());
		  j.put("lng", location.getLongtitute());
		  j.put("lat", location.getLatitute());
		return j;
	}
}
